/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the 'License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an 'AS IS' BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
import * as d3 from 'd3';
import * as _ from 'lodash';
import * as tf_graph_common from './common';
import { Class, FontSizeInPx, selectChild, selectOrCreateChild } from './common';
import * as contextmenu from './contextmenu';
import * as edge from './edge';
import * as tf_graph from './graph';
import * as tf_graph_proto from './proto';
import {
  BridgeNode,
  getIncludeNodeButtonString,
  Metanode,
  MetanodeImpl,
  Node,
  NodeType,
  OpNode,
  OpNodeImpl,
  SeriesNode,
} from './graph';
import * as layout from './layout';
import * as render from './render';
import { RenderNodeInfo } from './render';
import * as tf_graph_scene from './scene';
import { positionEllipse, positionRect } from './scene';
import { TfGraphScene } from './tf-graph-scene';
import * as tf_graph_util from './util';

/**
 * Select or Create a 'g.nodes' group to a given sceneGroup
 * and builds a number of 'g.node' groups inside the group.
 *
 * Structure Pattern:
 *
 * <g class='nodes'>
 *   <g class='node'>
 *     <g class='in-annotations'>
 *       ...
 *     </g>
 *     <g class='out-annotations'>
 *       ...
 *     </g>
 *     <g class='nodeshape'>
 *      <!--
 *      Content of the node shape should be for the node itself. For example a
 *      Metanode would have a <rect> with rounded edges, an op would have an
 *      <ellipse>. More complex nodes like series may contain multiple
 *      elements which are conditionally visible based on whether the node is
 *      expanded.
 *      -->
 *     </g>
 *     <text class='label'>node name</text>
 *     <g class='subscene'>
 *       <!--
 *       Content of  the subscene (only for metanode and series node).
 *
 *       Subscene is a svg group that contains content of the
 *       metanode's metagraph that is recursively generated by Scene.build().
 *
 *       When the graph is expanded multiple times, a subscene can contain
 *       nested subscenes inside.
 *       -->
 *     </g>
 *   </g>
 *   ...
 * </g>
 *
 *
 * @param sceneGroup selection of the container
 * @param nodeData array of render node information to map
 * @param sceneElement <tf-graph-scene> polymer element
 * @return selection of the created nodeGroups
 */
const colorStorage: { [key: string]: string } = {};
const matchStorage = [];
const unMatchStorage = [];
export function buildGroup(sceneGroup, nodeData: render.RenderNodeInfo[], sceneElement) {
  let container = tf_graph_common.selectOrCreateChild(sceneGroup, 'g', Class.Node.CONTAINER);
  // Select all children and join with data.
  // (Note that all children of g.nodes are g.node)
  let nodeGroups = (container as any)
    .selectAll(function () {
      return this.childNodes;
    })
    .data(nodeData, (d) => {
      // make sure that we don't have to swap shape type
      return d.node.name + ':' + d.node.type;
    });
  // ENTER
  nodeGroups
    .enter()
    .append('g')
    .attr('data-name', (d) => {
      return d.node.name;
    })
    .each(function (d) {
      let nodeGroup = d3.select(this);
      // index node group for quick stylizing
      sceneElement.addNodeGroup(d.node.name, nodeGroup);
    })
    .merge(nodeGroups)
    // ENTER + UPDATE
    .attr('class', (d) => {
      return Class.Node.GROUP + ' ' + nodeClass(d);
    })
    .each(function (d) {
      let nodeGroup = d3.select(this);
      // Add g.in-annotations (always add -- to keep layer order
      // consistent.)
      let inAnnotationBox = tf_graph_common.selectOrCreateChild(nodeGroup, 'g', Class.Annotation.INBOX);
      buildGroupForAnnotation(inAnnotationBox, d.inAnnotations, d, sceneElement);
      // Add g.out-annotations  (always add -- to keep layer order
      // consistent.)
      let outAnnotationBox = tf_graph_common.selectOrCreateChild(nodeGroup, 'g', Class.Annotation.OUTBOX);
      buildGroupForAnnotation(outAnnotationBox, d.outAnnotations, d, sceneElement);
      // Build .shape first (background of the node).
      let shape = buildShape(nodeGroup, d, Class.Node.SHAPE);
      let shape1 = buildShape(nodeGroup, d, Class.Node.OUTER);
      if (d.node.isGroupNode) {
        addButton(shape, d, sceneElement);
      }
      if (d.node.isGroupNode) {
        addButton(shape1, d, sceneElement);
      }
      addInteraction(shape, d, sceneElement);
      addInteraction(shape1, d, sceneElement);
      // Build subscene on the top.
      subsceneBuild(nodeGroup, <render.RenderGroupNodeInfo>d, sceneElement);
      // Build label last. Should be on top of everything else.
      let label = labelBuild(nodeGroup, d, sceneElement);
      // Do not add interaction to metanode labels as they live inside the
      // metanode shape which already has the same interactions.
      addInteraction(label, d, sceneElement, d.node.type === NodeType.META);
      stylize(nodeGroup, d, sceneElement);
      position(nodeGroup, d);
    });
  // EXIT
  nodeGroups
    .exit()
    .each(function (d) {
      // remove all indices on remove
      sceneElement.removeNodeGroup(d.node.name);
      let nodeGroup = d3.select(this);
      if (d.inAnnotations.list.length > 0) {
        nodeGroup
          .select('.' + Class.Annotation.INBOX)
          .selectAll('.' + Class.Annotation.GROUP)
          .each((a) => {
            sceneElement.removeAnnotationGroup(a, d);
          });
      }
      if (d.outAnnotations.list.length > 0) {
        nodeGroup
          .select('.' + Class.Annotation.OUTBOX)
          .selectAll('.' + Class.Annotation.GROUP)
          .each((a) => {
            sceneElement.removeAnnotationGroup(a, d);
          });
      }
    })
    .remove();
  return nodeGroups;
}
/**
 * Update or remove the subscene of a render group node depending on whether it
 * is a expanded. If the node is not a group node, this method has no effect.
 *
 * @param nodeGroup selection of the container
 * @param renderNodeInfo the render information for the node.
 * @param sceneElement <tf-graph-scene> polymer element.
 * @return Selection of the subscene group, or null if node group does not have
 *        a subscene. Op nodes, bridge nodes and unexpanded group nodes will
 *        not have a subscene.
 */
function subsceneBuild(nodeGroup, renderNodeInfo: render.RenderGroupNodeInfo, sceneElement: TfGraphScene) {
  if (renderNodeInfo.node.isGroupNode) {
    if (renderNodeInfo.expanded) {
      // Recursively build the subscene.
      return buildGroupForScene(nodeGroup, renderNodeInfo, sceneElement, Class.Subscene.GROUP);
    }
    // Clean out existing subscene if the node is not expanded.
    tf_graph_scene.selectChild(nodeGroup, 'g', Class.Subscene.GROUP).remove();
  }
  return null;
}
/**
 * Translate the subscene of the given node group
 */
function subscenePosition(nodeGroup, d: render.RenderNodeInfo) {
  // Translate the subscene to the middle of the parent node in vertical direction.
  let x0 = d.x - d.coreBox.width / 2;
  let y0 = d.y - d.height / 2 + d.paddingTop;
  let subscene = tf_graph_scene.selectChild(nodeGroup, 'g', Class.Subscene.GROUP);
  tf_graph_scene.translate(subscene, x0, y0);
}
/**
 * Add an expand/collapse button to a group node
 *
 * @param selection The group node selection.
 * @param d Info about the node being rendered.
 * @param sceneElement <tf-graph-scene> polymer element.
 */
function addButton(selection, d: render.RenderNodeInfo, sceneElement) {
  let group = tf_graph_common.selectOrCreateChild(selection, 'g', Class.Node.BUTTON_CONTAINER);
  tf_graph_common.selectOrCreateChild(group, 'circle', Class.Node.BUTTON_CIRCLE);
  tf_graph_common.selectOrCreateChild(group, 'path', Class.Node.EXPAND_BUTTON).attr('d', 'M0,-2.2 V2.2 M-2.2,0 H2.2');
  tf_graph_common.selectOrCreateChild(group, 'path', Class.Node.COLLAPSE_BUTTON).attr('d', 'M-2.2,0 H2.2');
  (group as any).on('click', (d: any) => {
    // Stop this event's propagation so that it isn't also considered a
    // node-select.
    (<Event>d3.event).stopPropagation();
    sceneElement.fire('node-toggle-expand', { name: d.node.name });
  });
  tf_graph_scene.positionButton(group, d);
}
/**
 * Fire node-* events when the selection is interacted.
 *
 * @param disableInteraction When true, have the provided selection
 * ignore all pointer events. Used for text labels inside of metanodes, which
 * don't need interaction as their surrounding shape has interaction, and if
 * given interaction would cause conflicts with the expand/collapse button.
 */
function addInteraction(selection, d: render.RenderNodeInfo, sceneElement: TfGraphScene, disableInteraction?: boolean) {
  if (disableInteraction) {
    selection.attr('pointer-events', 'none');
    return;
  }
  let contextMenuFunction = contextmenu.getMenu(sceneElement, getContextMenu(d.node, sceneElement), d);
  var time = 300;
  var timeOut;
  let mouseMoved = false;
  let startX, startY;
  const movementThreshold = 5;
  selection
    .on('dblclick', (d) => {
      clearTimeout(timeOut);
      sceneElement.fire('node-toggle-expand', { name: d.node.name });
    })
    .on('mouseover', (d) => {
      // don't send mouseover over expanded group,
      // otherwise it is causing too much glitches
      if (sceneElement.isNodeExpanded(d)) {
        return;
      }
      sceneElement.fire('node-highlight', { name: d.node.name });
    })
    .on('mouseout', (d) => {
      // don't send mouseover over expanded group,
      // otherwise it is causing too much glitches
      if (sceneElement.isNodeExpanded(d)) {
        return;
      }
      sceneElement.fire('node-unhighlight', { name: d.node.name });
    })
    .on('mousedown', () => {
      startX = d3.event.clientX;
      startY = d3.event.clientY;
      mouseMoved = false; // 重置标志变量
    })

    // 监听鼠标抬起事件，检查是否超过浮动阈值
    .on('mouseup', () => {
      const deltaX = Math.abs(d3.event.clientX - startX);
      const deltaY = Math.abs(d3.event.clientY - startY);
      if (deltaX > movementThreshold || deltaY > movementThreshold) {
        mouseMoved = true;
      }
    })

    .on('click', (d) => {
      clearTimeout(timeOut); // 清除第一个单击事件
      if (mouseMoved) {
        mouseMoved = false; // 重置标志变量
        return;
      }
      timeOut = setTimeout(function () {
        // (<Event>d3.event).stopPropagation();
        sceneElement.fire('node-select', { name: d.node.name });
      }, time);
    })
    // Stop this event's propagation so that it isn't also considered
    // a graph-select.

    .on('contextmenu', (d, i) => {
      sceneElement.fire('node-select', { name: d.node.name });
      contextMenuFunction.call(d, i);
    });
}
/**
 * Returns the d3 context menu specification for the provided node.
 */
export function getContextMenu(node: Node, sceneElement) {
  let menu = [
    {
      title: (d): string => {
        return getIncludeNodeButtonString(node.include);
      },
      action: (elm, d, i) => {
        sceneElement.fire('node-toggle-extract', { name: node.name });
      },
    },
  ];
  if (sceneElement.nodeContextMenuItems) {
    // Add these additional context menu items.
    menu = menu.concat(sceneElement.nodeContextMenuItems);
  }
  if (canBeInSeries(node)) {
    menu.push({
      title: (d) => {
        return getGroupSettingLabel(node);
      },
      action: (elm, d, i) => {
        sceneElement.fire('node-toggle-seriesgroup', {
          name: getSeriesName(node),
        });
      },
    });
  }
  return menu;
}
/** Returns if a node can be part of a grouped series */
export function canBeInSeries(node: Node) {
  return getSeriesName(node) !== null;
}
/**
 * Returns the name of the possible grouped series containing this node.
 * Returns null if the node cannot be part of a grouped series of nodes.
 */
export function getSeriesName(node: Node) {
  if (!node) {
    return null;
  }
  if (node.type === NodeType.SERIES) {
    return node.name;
  }
  if (node.type === NodeType.OP) {
    let op = <OpNode>node;
    return op.owningSeries;
  }
  return null;
}
/**
 * Returns the SeriesNode that represents the series that the provided node
 * is contained in (or itself if the provided node is itself a SeriesNode).
 * Returns null if the node is not rendered as part of a series.
 */
function getContainingSeries(node: Node) {
  let s: SeriesNode | null = null;
  if (!node) {
    return null;
  } else if (node.type === NodeType.SERIES) {
    s = <SeriesNode>node;
  } else if (node.parentNode && node.parentNode.type === NodeType.SERIES) {
    s = <SeriesNode>node.parentNode;
  }
  return s;
}
/**
 * Returns the label for a button to toggle the group setting of the provided
 * node.
 */
export function getGroupSettingLabel(node: Node) {
  return tf_graph.getGroupSeriesNodeButtonString(
    getContainingSeries(node) !== null ? tf_graph.SeriesGroupingType.GROUP : tf_graph.SeriesGroupingType.UNGROUP,
  );
}
/**
 * Append svg text for label and assign data.
 * @param nodeGroup
 * @param renderNodeInfo The render node information for the label.
 * @param sceneElement <tf-graph-scene> polymer element.
 */
function labelBuild(nodeGroup, renderNodeInfo: render.RenderNodeInfo, sceneElement) {
  let text = renderNodeInfo.displayName;
  // Truncate long labels for unexpanded Metanodes.
  let useFontScale = renderNodeInfo.node.type === (NodeType.META || NodeType.API_LIST) && !renderNodeInfo.expanded;
  let label = tf_graph_common.selectOrCreateChild(nodeGroup, 'text', Class.Node.LABEL);
  // Make sure the label is visually on top among its siblings.
  let labelNode = <HTMLElement>label.node();
  labelNode.parentNode?.appendChild(labelNode);
  label.attr('dy', '.35em').attr('text-anchor', 'middle');

  // In tf-graph-scene styles, fontSizes are defined to vary from 6px to 9px. Since we
  // do not want to invoke computedStyles or hardcode the fontSize that would be
  // duplicated in styles, we are rounding it to 8px which does not cause any visible
  // jank.
  let fontSize = 8;

  switch (renderNodeInfo.node.type) {
    case NodeType.META:
      fontSize = renderNodeInfo.expanded ? FontSizeInPx.Node.EXPANDED_LABEL : FontSizeInPx.Node.SERIES_LABEL;
      break;
    case NodeType.OP:
      fontSize = FontSizeInPx.Node.OP_LABEL;
      break;
    case NodeType.API_LIST:
      fontSize = renderNodeInfo.expanded ? FontSizeInPx.Node.EXPANDED_LABEL : FontSizeInPx.Node.SERIES_LABEL;
      break;
  }

  if (useFontScale) {
    if (text.length > sceneElement.maxMetanodeLabelLength) {
      text = text.substr(0, sceneElement.maxMetanodeLabelLength - 2) + '…';
    }
    let scale = getLabelFontScale(sceneElement);
    label.attr('font-size', scale(text.length) + 'px');
    fontSize = scale(text.length);
  }
  let txtElement = <d3.Selection<any, any, any, any>>label.text(text);
  enforceLabelWidth(txtElement, renderNodeInfo.node.type, fontSize, renderNodeInfo);
  return label;
}

/**
 * This function shortens text which would exceed the maximum pixel width of
 * a label.
 *
 * @param txtElementSelection The text element containing the label's text as d3
 * selection.
 * @param nodeType The type of the node the label belongs to. If the node is
 * an annotation, the value is -1. Label widths are defined in
 * layout.PARAMS.nodeSize.{meta|op|...}.maxLabelWidth for nodes and
 * layout.PARAMS.annotations.labelWidth for annotations.
 * @param renderNodeInfo The render information about the node, required to
 * determine whether META nodes are collapsed or expanded.
 */
export function enforceLabelWidth(
  txtElementSelection: d3.Selection<any, any, any, any>,
  nodeType: NodeType | number,
  fontSize: number,
  renderNodeInfo?: render.RenderNodeInfo,
): any {
  // Get text element itself and its on-screen width.
  let txtNode = <SVGTextElement>txtElementSelection.node();
  let labelContent = txtNode.textContent;

  // Get maximum length from settings.
  let maxLength: number | null = null;
  switch (nodeType) {
    case NodeType.META:
      if (renderNodeInfo && !renderNodeInfo.expanded) {
        // Only trim text if
        // node expanded.
        maxLength = layout.PARAMS.nodeSize.meta.maxLabelWidth;
      }
      break;
    case NodeType.API_LIST:
      if (renderNodeInfo && !renderNodeInfo.expanded) {
        // Only trim text if
        // node expanded.
        maxLength = layout.PARAMS.nodeSize.api_list.maxLabelWidth;
      }
      break;
    case NodeType.OP:
      maxLength = layout.PARAMS.nodeSize.op.maxLabelWidth;
      break;
    case -1:
      maxLength = layout.PARAMS.annotations.maxLabelWidth;
      break;
    default:
      break;
  }
  if (maxLength === null) return;

  txtNode.textContent = tf_graph_util.maybeTruncateString(txtNode.textContent!, fontSize, maxLength);
  // Add tooltip with full name and return.
  return txtElementSelection.append('title').text(labelContent!);
}
/**
 * d3 scale used for sizing font of labels, used by labelBuild,
 * initialized once by getLabelFontScale.
 */
let fontScale: any = null;
function getLabelFontScale(sceneElement) {
  if (!fontScale) {
    fontScale = d3
      .scaleLinear()
      .domain([sceneElement.maxMetanodeLabelLengthLargeFont, sceneElement.maxMetanodeLabelLength])
      .range([sceneElement.maxMetanodeLabelLengthFontSize, sceneElement.minMetanodeLabelLengthFontSize])
      .clamp(true);
  }
  return fontScale;
}
/**
 * Set label position of a given node group
 */
function labelPosition(nodeGroup, cx: number, cy: number, yOffset: number) {
  tf_graph_scene
    .selectChild(nodeGroup, 'text', Class.Node.LABEL)
    .transition()
    .attr('x', cx)
    .attr('y', cy + yOffset);
}
/**
 * Select or append/insert shape for a node and assign renderNode
 * as the shape's data.
 *
 * @param nodeGroup
 * @param d Render node information.
 * @param nodeClass class for the element.
 * @return Selection of the shape.
 */
export function buildShape(nodeGroup, d, nodeClass: string): d3.Selection<any, any, any, any> {
  // Create a group to house the underlying visual elements.
  let shapeGroup = tf_graph_common.selectOrCreateChild(nodeGroup, 'g', nodeClass);
  // TODO: DOM structure should be templated in HTML somewhere, not JS.
  switch (d.node.type) {
    case NodeType.OP:
      const opNode = d.node as OpNode;
      if (_.isNumber(opNode.functionInputIndex) || _.isNumber(opNode.functionOutputIndex)) {
        // This is input or output arg for a TensorFlow function. Use a special
        // shape (a triangle) for them.
        tf_graph_common.selectOrCreateChild(shapeGroup, 'polygon', Class.Node.COLOR_TARGET);
        break;
      }
      tf_graph_common.selectOrCreateChild(shapeGroup, 'ellipse', Class.Node.COLOR_TARGET);
      break;
    case NodeType.SERIES:
      // Choose the correct stamp to use to represent this series.
      let stampType = 'annotation';
      let groupNodeInfo = <render.RenderGroupNodeInfo>d;
      if (groupNodeInfo.coreGraph) {
        stampType = groupNodeInfo.node.hasNonControlEdges ? 'vertical' : 'horizontal';
      }
      let classList = [Class.Node.COLOR_TARGET];
      if (groupNodeInfo.isFadedOut) {
        classList.push('faded-ellipse');
      }
      tf_graph_common
        .selectOrCreateChild(shapeGroup, 'use', classList)
        .attr('xlink:href', '#op-series-' + stampType + '-stamp');
      tf_graph_common
        .selectOrCreateChild(shapeGroup, 'rect', Class.Node.COLOR_TARGET)
        .attr('rx', d.radius)
        .attr('ry', d.radius);
      break;
    case NodeType.BRIDGE:
      tf_graph_common
        .selectOrCreateChild(shapeGroup, 'rect', Class.Node.COLOR_TARGET)
        .attr('rx', d.radius)
        .attr('ry', d.radius);
      break;
    case NodeType.META:
      tf_graph_common
        .selectOrCreateChild(shapeGroup, 'rect', Class.Node.COLOR_TARGET)
        .attr('rx', d.radius)
        .attr('ry', d.radius);
      break;
    case NodeType.API_LIST:
      tf_graph_common
        .selectOrCreateChild(shapeGroup, 'rect', Class.Node.COLOR_TARGET)
        .attr('rx', d.radius)
        .attr('ry', d.radius);
      break;
    default:
      throw Error('Unrecognized node type 3: ' + d.node.type);
  }
  return shapeGroup;
}
export function nodeClass(d: render.RenderNodeInfo) {
  switch (d.node.type) {
    case NodeType.OP:
      return Class.OPNODE;
    case NodeType.META:
      return Class.METANODE;
    case NodeType.SERIES:
      return Class.SERIESNODE;
    case NodeType.BRIDGE:
      return Class.BRIDGENODE;
    case NodeType.ELLIPSIS:
      return Class.ELLIPSISNODE;
    case NodeType.API_LIST:
      return Class.API_LIST;
  }
  throw Error('Unrecognized node type: ' + d.node.type);
}
/** Modify node and its subscene and its label's positional attributes */
function position(nodeGroup, d: render.RenderNodeInfo) {
  let shapeGroup = tf_graph_scene.selectChild(nodeGroup, 'g', Class.Node.SHAPE);
  let shapeGroup1 = tf_graph_scene.selectChild(nodeGroup, 'g', Class.Node.OUTER);
  let cx = layout.computeCXPositionOfNodeShape(d);
  switch (d.node.type) {
    case NodeType.OP: {
      // position shape
      const opNode = d.node as OpNode;
      if (_.isNumber(opNode.functionInputIndex) || _.isNumber(opNode.functionOutputIndex)) {
        // This shape represents the input into or output out of a TensorFlow
        // function.
        let shape = tf_graph_scene.selectChild(shapeGroup, 'polygon');
        tf_graph_scene.positionTriangle(shape, d.x, d.y, d.coreBox.width, d.coreBox.height);
      } else {
        let shape = tf_graph_scene.selectChild(shapeGroup, 'ellipse');
        tf_graph_scene.positionEllipse(shape, cx, d.y, d.coreBox.width, d.coreBox.height);
      }
      labelPosition(nodeGroup, cx, d.y, d.labelOffset);
      break;
    }
    case NodeType.META: {
      // position shape
      let shapes = shapeGroup.selectAll('rect');
      let INSIDE_RECT_OFFSET = 0;
      if (d.expanded) {
        tf_graph_scene.positionRect(shapes, d.x, d.y, d.width, d.height);
        // y值为定位值 取值为（15/2 (中心点y值) + 0.6 (向下偏移值, 不偏移会覆盖边及其颜色)）得出
        INSIDE_RECT_OFFSET = d.y - (d.height / 2) + 8.1
        subscenePosition(nodeGroup, d);
        // Put the label on top.
        labelPosition(nodeGroup, cx, d.y, -d.height / 2 + d.labelHeight / 2);
      } else {
        tf_graph_scene.positionRect(shapes, cx, d.y, d.coreBox.width, d.coreBox.height);
        // Place the label in the middle.
        labelPosition(nodeGroup, cx, d.y, 0);
      }
      let shapes1 = shapeGroup1.selectAll('rect');
      if (d.expanded) {
        tf_graph_scene.positionRect(shapes1, d.x, INSIDE_RECT_OFFSET, d.width - 1, 15);
        subscenePosition(nodeGroup, d);
        // Put the label on top.
        labelPosition(nodeGroup, cx, d.y, -d.height / 2 + d.labelHeight / 2);
      } else {
        tf_graph_scene.positionRect(shapes1, cx, d.y, d.coreBox.width, d.coreBox.height);
        // Place the label in the middle.
        labelPosition(nodeGroup, cx, d.y, 0);
      }
      break;
    }
    case NodeType.SERIES: {
      let shape = tf_graph_scene.selectChild(shapeGroup, 'use');
      if (d.expanded) {
        tf_graph_scene.positionRect(shape, d.x, d.y, d.width, d.height);
        subscenePosition(nodeGroup, d);
        // put label on top
        labelPosition(nodeGroup, cx, d.y, -d.height / 2 + d.labelHeight / 2);
      } else {
        tf_graph_scene.positionRect(shape, cx, d.y, d.coreBox.width, d.coreBox.height);
        labelPosition(nodeGroup, cx, d.y, d.labelOffset);
      }
      break;
    }
    case NodeType.BRIDGE: {
      // position shape
      // NOTE: In reality, these will not be visible, but it helps to put them
      // in the correct position for debugging purposes.
      let shape = tf_graph_scene.selectChild(shapeGroup, 'rect');
      tf_graph_scene.positionRect(shape, d.x, d.y, d.width, d.height);
      break;
    }
    case NodeType.API_LIST: {
      // position shape
      let shapes = shapeGroup.selectAll('rect');
      if (d.expanded) {
        tf_graph_scene.positionRect(shapes, d.x, d.y, d.width, d.height);
        subscenePosition(nodeGroup, d);
        // Put the label on top.
        labelPosition(nodeGroup, cx, d.y, -d.height / 2 + d.labelHeight / 2);
      } else {
        tf_graph_scene.positionRect(shapes, cx, d.y, d.coreBox.width, d.coreBox.height);
        // Place the label in the middle.
        labelPosition(nodeGroup, cx, d.y, 0);
      }
      break;
    }
    default: {
      throw Error('Unrecognized node type: ' + d.node.type);
    }
  }
}

function getGradient(
  id: string,
  colors: Array<{
    color: string;
    proportion: number;
  }>,
  svgRoot?: SVGElement,
): string {
  let escapedId = tf_graph_util.escapeQuerySelector(id);
  if (!svgRoot) return `url(#${escapedId})`;
  let $svgRoot = d3.select(svgRoot);
  let gradientDefs = $svgRoot.select('defs#_graph-gradients');
  if (gradientDefs.empty()) {
    gradientDefs = $svgRoot.append('defs').attr('id', '_graph-gradients');
  }
  let linearGradient = gradientDefs.select('linearGradient#' + escapedId);
  // If the linear gradient is not there yet, create it.
  if (linearGradient.empty()) {
    linearGradient = gradientDefs.append('linearGradient').attr('id', id);
    // Re-create the stops of the linear gradient.
    linearGradient.selectAll('*').remove();
    let cumulativeProportion = 0;
    // For each color, create a stop using the proportion of that device.
    _.each(colors, (d) => {
      let color = d.color;
      linearGradient.append('stop').attr('offset', cumulativeProportion).attr('stop-color', color);
      linearGradient
        .append('stop')
        .attr('offset', cumulativeProportion + d.proportion)
        .attr('stop-color', color);
      cumulativeProportion += d.proportion;
    });
  }
  return `url(#${escapedId})`;
}
export function removeGradientDefinitions(svgRoot: SVGElement) {
  d3.select(svgRoot).select('defs#_graph-gradients').remove();
}

function getColorByPrecisionIndex(precisionStr: string): string {
  const precision = Number(precisionStr);
  if (Object.entries(colorStorage).length != 0) {
    for (const [color, details] of Object.entries(colorStorage)) {
      const detailsArray: any[] = [details];
      const [start, end] = detailsArray[0].value;
      //进入md5模式
      if (start == end) {
        if (precision == start) {
          return color;
        }
      }
      //对对比匹配成功的节点进行校验，如果precision大于1，按照最高等级处理，及颜色列表倒数第二个，倒数第一是未匹配节点的灰色
      else if (precision >= 1) {
        const lastColor = Object.entries(colorStorage)[Object.entries(colorStorage).length - 2][0];
        return lastColor;
      }
      //其他区间模式, 最后一个区间的右侧一定为1，所以特化precision == 1的情况
      else if ((precision >= start && precision < end) || (precision == end && end == 1)) {
        return color;
      }
    }
    return 'white';
  } else {
    if (isNaN(precision)) {
      return 'white';
    }
    if (precision <= 0.2) {
      return '#ff704d';
    } else if (precision <= 0.4) {
      return '#FFC62E';
    } else if (precision <= 0.6) {
      return '#FFDC7F';
    } else if (precision <= 0.8) {
      return '#FFEDBE';
    } else {
      return '#FFFCF3';
    }
  }
}

/**
 * Returns the fill color for the node given its state and the 'color by'
 * option.
 * Takes in optional svgRoot, when passed, that populates SVG definitions
 * for the fill inside the svgRoot when necessary.
 */
export function getFillForNode(renderInfo: render.RenderNodeInfo): string {
  if (renderInfo.node instanceof OpNodeImpl || renderInfo.node instanceof MetanodeImpl) {
    const precision_item = renderInfo.node.attr.find((item) => item.key === tf_graph.PRECISION_INDEX);
    const matched_node_link = renderInfo.node.matchedNodeLink; //标杆侧没有任何颜色
    const result = matchStorage.find((item) => Array.isArray(item) && item[0] === renderInfo.node.name);
    const unmatch = unMatchStorage.find((item) => item == renderInfo.node.name);
    if (result) {
      return getColorByPrecisionIndex(result[1]);
    }
    if (unmatch) {
      return '#C7C7C7';
    }
    // 以前缀来判断是单图节点还是对比图节点
    if (renderInfo.node.name.startsWith('B___') || renderInfo.node.name.startsWith('N___')) {
      if (!matched_node_link && !renderInfo.node.name.startsWith('B___')) {
        return '#C7C7C7';
      }
    }
    if (precision_item) {
      return getColorByPrecisionIndex(precision_item.value);
    } else {
      return 'transparent';
    }
  } else {
    // Other nodes are white.
    return 'transparent';
  }
}
/**
 * Modify node style by toggling class and assign attributes (only for things
 * that can't be done in css).
 */
export function stylize(nodeGroup, renderInfo: render.RenderNodeInfo, sceneElement: TfGraphScene, nodeClass?) {
  nodeClass = nodeClass || Class.Node.SHAPE || Class.Node.OUTER;
  const isHighlighted = sceneElement.isNodeHighlighted(renderInfo.node.name);
  const isSelected = sceneElement.isNodeSelected(renderInfo.node.name);
  const isExtract = renderInfo.isInExtract || renderInfo.isOutExtract || renderInfo.isLibraryFunction;
  const isExpanded = renderInfo.expanded && nodeClass !== Class.Annotation.NODE;
  const isFadedOut = renderInfo.isFadedOut;
  const isLinked = sceneElement.isNodeLinked(renderInfo.node.name);
  nodeGroup.classed('highlighted', isHighlighted);
  nodeGroup.classed('selected', isSelected);
  nodeGroup.classed('extract', isExtract);
  nodeGroup.classed('expanded', isExpanded);
  nodeGroup.classed('faded', isFadedOut);
  nodeGroup.classed('linked', isLinked);
  // Main node always exists here and it will be reached before subscene,
  // so d3 selection is fine here.OLOR_TARGET)
  const node = nodeGroup.select('.' + nodeClass + ' .' + Class.Node.COLOR_TARGET);
  const node1 = nodeGroup.select('.' + Class.Node.OUTER + ' .' + Class.Node.COLOR_TARGET);
  const fillColor = getFillForNode(renderInfo);
  if (renderInfo.node.type == 0) {
    node.style('fill', 'white');
    node1.style('fill', fillColor);
  } else {
    node.style('fill', fillColor);
  }
  // Choose outline to be darker version of node color if the node is a single
  // color and is not selected.
  node.style('stroke', isSelected ? null : getStrokeForFill(fillColor === 'transparent' ? 'white' : fillColor));
}
/**
 * Given a node's fill color/gradient, determine the stroke for the node.
 */
export function getStrokeForFill(fill: string) {
  // If node is colored by a gradient, then use a dark gray outline.
  if (fill.substring(0, 3) === 'url') {
    return render.MetanodeColors.GRADIENT_OUTLINE;
  } else if (fill.startsWith('rgba')) {
    return 'rgb(167, 167, 167)';
  } else {
    return d3.rgb(fill).darker().toString();
  }
}
/**
 * Finds selected node and highlights all nodes which are providing direct
 * or indirect input to the node and all edges connecting these nodes
 * together and to the selected node.
 */
export function updateInputTrace(
  svgRoot: SVGElement,
  renderGraphInfo: render.RenderGraphInfo,
  selectedNodeName: string,
  traceInputs: Boolean,
) {
  // Reset all styling.
  const svg = d3.select(svgRoot);
  svg.selectAll('.input-highlight').classed('input-highlight', false);
  svg.selectAll('.non-input').classed('non-input', false);
  svg.selectAll('.input-parent').classed('input-parent', false);
  svg.selectAll('.input-child').classed('input-child', false);
  svg.selectAll('.input-edge-highlight').classed('input-edge-highlight', false);
  svg.selectAll('.non-input-edge-highlight').classed('non-input-edge-highlight', false);
  svg.selectAll('.input-highlight-selected').classed('input-highlight-selected', false);
  // Extract currently selected node. Return if input tracing disabled or no
  // node is selected.
  if (!renderGraphInfo || !traceInputs || !selectedNodeName) {
    return;
  }
  let opNodes = _getAllContainedOpNodes(selectedNodeName, renderGraphInfo);
  let allTracedNodes = {};
  _.each(opNodes, function (nodeInstance) {
    allTracedNodes = traceAllInputsOfOpNode(svgRoot, renderGraphInfo, nodeInstance, allTracedNodes);
  });
  // Highlight all parent nodes of each OpNode as input parent to allow
  // specific highlighting.
  let highlightedNodes = Object.keys(allTracedNodes);
  let visibleNodes = _findVisibleParentsFromOpNodes(renderGraphInfo, highlightedNodes);
  _markParentsOfNodes(svgRoot, visibleNodes);
  // Attach class to all non-input nodes and edges for styling.
  svg
    .selectAll('g.node:not(.selected):not(.input-highlight)' + ':not(.input-parent):not(.input-children)')
    .classed('non-input', true)
    .each(function (d: RenderNodeInfo) {
      // Mark all nodes with the specified name as non-inputs. This
      // results in Annotation nodes which are attached to inputs to be
      // tagged as well.
      let nodeName = d.node.name;
      svg.selectAll(`[data-name="${nodeName}"]`).classed('non-input', true);
    });
  svg.selectAll('g.edge:not(.input-edge-highlight)').classed('non-input-edge-highlight', true);
}
/**
 * Recursively find all op nodes contained by the node identified by the
 * provided name.
 * @param nodeName The meta or op node of which the OpNode instances are
 * required.
 * @param renderGraphInfo The rendered graph information object.
 * @returns {Array} An array of OpNodeImpl instances.
 */
function _getAllContainedOpNodes(nodeName: string, renderGraphInfo: render.RenderGraphInfo): ReadonlyArray<OpNodeImpl> {
  let opNodes: OpNodeImpl[] = [];
  // Get current node.
  let node = renderGraphInfo.getNodeByName(nodeName) as tf_graph.GroupNode | tf_graph.OpNode;
  // If node is already OpNode then return the node plus its input embeddings.
  if (node instanceof tf_graph.OpNodeImpl) {
    return [node].concat(node.inEmbeddings);
  }
  // Otherwise, make recursive call for each node contained by the GroupNode.
  let childNodeNames = (node as tf_graph.GroupNode).metagraph.nodes();
  _.each(childNodeNames, function (childNodeName) {
    opNodes = opNodes.concat(_getAllContainedOpNodes(childNodeName, renderGraphInfo));
  });
  return opNodes;
}
/**
 * When resolving inputs of a node the visible parent node of each input
 * node (i.e. the first parent which is rendered to the screen) needs to be
 * found, and since such a node may contain several input OpNodes a map
 * of the visible parent to all the input OpNodes it contains is provided by
 * opNodes.
 */
interface VisibleParent {
  visibleParent: Node;
  opNodes: OpNode[];
}
function traceAllInputsOfOpNode(
  svgRoot: SVGElement,
  renderGraphInfo: render.RenderGraphInfo,
  startNode: OpNode,
  allTracedNodes: Object,
) {
  // To prevent infinite loops due to cyclical relationships and improving
  // performance by tracing OpNode which is input to 2+ nodes only once.
  if (allTracedNodes[startNode.name]) {
    return allTracedNodes;
  } else {
    allTracedNodes[startNode.name] = true;
  }
  // Extract the inputs.
  let inputs = startNode.inputs;
  // Get visible parent.
  let currentVisibleParent = getVisibleParent(renderGraphInfo, startNode);
  // Mark as input node.
  d3.select(svgRoot).select(`.node[data-name="${currentVisibleParent.name}"]`).classed('input-highlight', true);
  // Find the visible parent of each input.
  let visibleInputs = {};
  _.each(inputs, function (nodeInstance) {
    let resolvedNode = renderGraphInfo.getNodeByName(nodeInstance.name);
    if (resolvedNode === undefined) {
      // Node could not be found in rendered Hierarchy, which happens when
      // tracing inputs of a SummaryNode.
      return;
    }
    // Ensure node is resolved to OpNode if name collision with Metanode exists.
    if (resolvedNode instanceof MetanodeImpl) {
      let resolvedNodeName = tf_graph.getStrictName(resolvedNode.name);
      resolvedNode = renderGraphInfo.getNodeByName(resolvedNodeName) as OpNode;
    }
    let visibleParent = getVisibleParent(renderGraphInfo, resolvedNode);
    // Append OpNode to visible parent entry.
    let visibleInputsEntry = visibleInputs[visibleParent.name];
    if (visibleInputsEntry) {
      visibleInputsEntry.opNodes.push(resolvedNode);
    } else {
      // Create new entry.
      visibleInputs[visibleParent.name] = {
        visibleParent: visibleParent,
        opNodes: [resolvedNode],
      } as VisibleParent;
    }
  });
  // Find all parents of the start node.
  let startNodeParents = {};
  let indexedStartNodeParents = [currentVisibleParent];
  startNodeParents[currentVisibleParent.name] = {
    traced: false,
    index: 0,
    connectionEndpoints: [],
  };
  let currentNode = currentVisibleParent as Node;
  for (let index = 1; currentNode.name !== tf_graph.ROOT_NAME; index++) {
    currentNode = currentNode.parentNode;
    startNodeParents[currentNode.name] = {
      traced: false,
      index: index,
      connectionEndpoints: [],
    };
    indexedStartNodeParents[index] = currentNode;
  }
  // Find first mutual parent of each input node and highlight connection.
  _.forOwn(visibleInputs, function (visibleParentInfo: VisibleParent, key) {
    let nodeInstance = visibleParentInfo.visibleParent;
    // Make recursive call for each input-OpNode contained by the visible
    // parent.
    _.each(visibleParentInfo.opNodes, function (opNode: OpNode) {
      allTracedNodes = traceAllInputsOfOpNode(svgRoot, renderGraphInfo, opNode, allTracedNodes);
    });
    if (nodeInstance.name !== currentVisibleParent.name) {
      _createVisibleTrace(svgRoot, nodeInstance, startNodeParents, indexedStartNodeParents);
    }
  });
  return allTracedNodes;
}
/**
 * Colors the edges to connect the passed node to the start node. This is
 * done by:
 *
 * a) Finding the first (visible) common parent in the rendered
 * hierarchy.
 * NB: There are 2 types of connections:
 * 1) Direct connections between node A
 * and B, marked below as II,
 * 2) Connections from any node A to its parent, A'. Marked below as I and III.
 * For type 2 connection you need to know the inner-nested node, the
 * direct parent, and the ultimate destination of the connection.
 *
 *  A_parent      B_parent
 * +--------+    +---------+
 * |        |    |         |
 * |  +--+ I| II |III+--+  |
 * |  |A +---------->+B |  |
 * |  +--+  |    |   +--+  |
 * |        |    |         |
 * +--------+    +---------+
 *
 *
 * b) Highlighting the direct connection between the parents of A and B,
 * called A_parent and B_parent, s.t. A_parent and B_parent are children of the
 * mutual parent of A and B found in a), marked above as II.
 *
 * c) Highlighting the connection from A to A_parent and B to B_parent
 * (through all layers of parents between A and A_parent and B and B_parent,
 * respectively). Marked above as I and III.
 *
 * @param nodeInstance The instance of the node to use as destination node, B.
 * @param startNodeParents Map of startNodeParent names to information objects
 * about the parent.
 * @param indexedStartNodeParents An array of all parents of the start node.
 * This is required to find the child of the mutual parent which is a parent
 * of the start node.
 * @private
 */
function _createVisibleTrace(
  svgRoot: SVGElement,
  nodeInstance: Node,
  startNodeParents,
  indexedStartNodeParents: Node[],
) {
  let currentNode = nodeInstance;
  let previousNode = nodeInstance;
  // Ascend through parents until a mutual parent is found with the start
  // node.
  let destinationParentPairs: Node[][] = [];
  while (!startNodeParents[currentNode.name]) {
    if (previousNode.name !== currentNode.name) {
      destinationParentPairs.push([previousNode, currentNode]);
    }
    previousNode = currentNode;
    currentNode = currentNode.parentNode;
  }
  // Connection between nodes is drawn between the parents of each
  // respective node, both of which share the mutual parent.
  let startNodeIndex = startNodeParents[currentNode.name].index;
  let startNodeName = indexedStartNodeParents[Math.max(startNodeIndex - 1, 0)].name;
  let startNodeTopParentName = startNodeName;
  let targetNodeTopParentName = previousNode.name;
  let endNodeName = previousNode.name;
  const svg = d3.select(svgRoot);
  svg.selectAll(`[data-edge="${endNodeName}--${startNodeName}"]`).classed('input-edge-highlight', true);
  // Trace up the parents of the input.
  _.each(destinationParentPairs, function (value) {
    let inner = value[0];
    let outer = value[1];
    let edgeSelector = `[data-edge="${inner.name}--${startNodeTopParentName}` + `~~${outer.name}~~OUT"]`;
    svg.selectAll(edgeSelector).classed('input-edge-highlight', true);
  });
  // Trace up the parents of the start node.
  for (let index = 1; index < startNodeIndex; index++) {
    let inner = indexedStartNodeParents[index - 1];
    let outer = indexedStartNodeParents[index];
    let edgeSelector = `[data-edge="${targetNodeTopParentName}~~${outer.name}` + `~~IN--${inner.name}"]`;
    svg.selectAll(edgeSelector).classed('input-edge-highlight', true);
  }
}
/**
 * Creates map { [name: string] -> Node } of all visible / rendered parents
 * of the nodes identified by the node names passed in.
 *
 * @param renderGraphInfo The information on the rendered graph.
 * @param nodeNames String array of node names.
 * @returns {[nodeName: string]: Node}
 * @private
 */
function _findVisibleParentsFromOpNodes(renderGraphInfo, nodeNames: string[]) {
  let visibleParents: {
    [nodeName: string]: Node;
  } = {};
  _.each(nodeNames, function (nodeName) {
    let currentNode = renderGraphInfo.getNodeByName(nodeName);
    let visibleParent = getVisibleParent(renderGraphInfo, currentNode);
    visibleParents[visibleParent.name] = visibleParent;
  });
  return visibleParents;
}
/**
 * Traverse through the parents of all nodes in the list and mark each
 * encountered node as input-parent.
 * @param visibleNodes Map of input nodes, have to be visible/rendered when
 * called.
 * @private
 */
function _markParentsOfNodes(
  svgRoot: SVGElement,
  visibleNodes: {
    [nodeName: string]: Node;
  },
) {
  _.forOwn(visibleNodes, function (nodeInstance: Node) {
    // Mark all parents of the node as input-parents.
    let currentNode = nodeInstance;
    while (currentNode.name !== tf_graph.ROOT_NAME) {
      const renderedElementSelection = d3.select(svgRoot).select(`.node[data-name="${currentNode.name}"]`);
      // Only mark the element as a parent node to an input if it is not
      // marked as input node itself.
      if (
        renderedElementSelection.nodes().length &&
        !renderedElementSelection.classed('input-highlight') &&
        !renderedElementSelection.classed('selected') &&
        // OpNode only parent if start node is embedded node, in which case
        // the OpNode should be faded as well.
        !renderedElementSelection.classed('op')
      ) {
        renderedElementSelection.classed('input-parent', true);
      }
      currentNode = currentNode.parentNode;
    }
  });
}
/**
 * Find the parent of the passed in op node which is expanded. This is done
 * by going through all parents until the parent's parent is expanded, thus
 * finding the first unexpanded parent which is rendered on the screen.
 * @param renderGraphInfo The graph info object used to gain access to the
 * render info of the parents.
 * @param currentNode The node whose parent is to be found.
 * @returns Node
 */
export function getVisibleParent(renderGraphInfo: render.RenderGraphInfo, currentNode: tf_graph.Node) {
  let found = false;
  let currentParent = currentNode;
  while (!found) {
    // Get parent element, to extract name.
    currentNode = currentParent;
    currentParent = currentNode.parentNode;
    if (currentParent === undefined) {
      found = true;
    } else {
      let renderNode = renderGraphInfo.getRenderNodeByName(currentParent.name);
      // Found if node is rendered on the screen (renderNode truthy), and
      // the parent is either expanded (i.e. it is a metanode or seriesnode)
      // or the parent is an OpNode in which case currentNode is an embedded
      // node which has another OpNode as parent.
      if (renderNode && (renderNode.expanded || currentParent instanceof tf_graph.OpNodeImpl)) {
        found = true;
      }
    }
  } // Close while loop.
  return currentNode;
}

/**
 * Annotations.
 */

export function buildGroupForAnnotation(
  container,
  annotationData: render.AnnotationList,
  d: render.RenderNodeInfo,
  sceneElement,
) {
  // Select all children and join with data.
  let annotationGroups = container
    .selectAll(function () {
      // using d3's selector function
      // See https://github.com/mbostock/d3/releases/tag/v2.0.0
      // (It's not listed in the d3 wiki.)
      return this.childNodes;
    })
    .data(annotationData.list, (d) => {
      return d.node.name;
    });
  annotationGroups
    .enter()
    .append('g')
    .attr('data-name', (a) => {
      return a.node.name;
    })
    .each(function (a) {
      let aGroup = d3.select(this);
      // Add annotation to the index in the scene
      sceneElement.addAnnotationGroup(a, d, aGroup);
      // Append annotation edge
      let edgeType = Class.Annotation.EDGE;
      let metaedge = a.renderMetaedgeInfo && a.renderMetaedgeInfo.metaedge;
      if (metaedge && !metaedge.numRegularEdges) {
        edgeType += ' ' + Class.Annotation.CONTROL_EDGE;
      }
      // If any edges are reference edges, add the reference edge class.
      if (metaedge && metaedge.numRefEdges) {
        edgeType += ' ' + Class.Edge.REF_LINE;
      }
      edge.appendEdge(aGroup, a, sceneElement, edgeType);
      if (a.annotationType !== render.AnnotationType.ELLIPSIS) {
        addAnnotationLabelFromNode(aGroup, a);
        buildShapeForAnnotation(aGroup, a);
      } else {
        addAnnotationLabel(aGroup, a.node.name, a, Class.Annotation.ELLIPSIS);
      }
    })
    .merge(annotationGroups)
    .attr('class', (a) => {
      return Class.Annotation.GROUP + ' ' + annotationToClassName(a.annotationType) + ' ' + nodeClass(a);
    })
    .each(function (a) {
      let aGroup = d3.select(this);
      update(aGroup, d, a, sceneElement);
      if (a.annotationType !== render.AnnotationType.ELLIPSIS) {
        addInteractionForAnnotation(aGroup, d, a, sceneElement);
      }
    });
  annotationGroups
    .exit()
    .each(function (a) {
      // Remove annotation from the index in the scene
      sceneElement.removeAnnotationGroup(a, d);
    })
    .remove();
  return annotationGroups;
}
/**
 * Maps an annotation enum to a class name used in css rules.
 */
function annotationToClassName(annotationType: render.AnnotationType) {
  return (render.AnnotationType[annotationType] || '').toLowerCase() || null;
}
function buildShapeForAnnotation(aGroup, a: render.Annotation) {
  if (a.annotationType === render.AnnotationType.SUMMARY) {
    let summary = selectOrCreateChild(aGroup, 'use');
    summary.attr('class', 'summary').attr('xlink:href', '#summary-icon').attr('cursor', 'pointer');
  } else {
    let shape = buildShape(aGroup, a, Class.Annotation.NODE);
    // add title tag to get native tooltips
    selectOrCreateChild(shape, 'title').text(a.node.name);
  }
}
function addAnnotationLabelFromNode(aGroup, a: render.Annotation) {
  let namePath = a.node.name.split('/');
  let text = namePath[namePath.length - 1];
  return addAnnotationLabel(aGroup, text, a, null);
}
function addAnnotationLabel(aGroup, label: string, a: render.Annotation, additionalClassNames) {
  let classNames = Class.Annotation.LABEL;
  if (additionalClassNames) {
    classNames += ' ' + additionalClassNames;
  }
  let txtElement = aGroup
    .append('text')
    .attr('class', classNames)
    .attr('dy', '.35em')
    .attr('text-anchor', a.isIn ? 'end' : 'start')
    .text(label);
  return enforceLabelWidth(txtElement, -1, FontSizeInPx.Annotation.LABEL);
}
function addInteractionForAnnotation(selection, d: render.RenderNodeInfo, annotation: render.Annotation, sceneElement) {
  selection
    .on('mouseover', (a) => {
      sceneElement.fire('annotation-highlight', {
        name: a.node.name,
        hostName: d.node.name,
      });
    })
    .on('mouseout', (a) => {
      sceneElement.fire('annotation-unhighlight', {
        name: a.node.name,
        hostName: d.node.name,
      });
    })
    .on('click', (a) => {
      // Stop this event's propagation so that it isn't also considered a
      // graph-select.
      (<Event>d3.event).stopPropagation();
      sceneElement.fire('annotation-select', {
        name: a.node.name,
        hostName: d.node.name,
      });
    });
  if (
    annotation.annotationType !== render.AnnotationType.SUMMARY &&
    annotation.annotationType !== render.AnnotationType.CONSTANT
  ) {
    selection.on('contextmenu', contextmenu.getMenu(sceneElement, getContextMenu(annotation.node, sceneElement)), d);
  }
}
/**
 * Adjust annotation's position.
 *
 * @param aGroup selection of a 'g.annotation' element.
 * @param d Host node data.
 * @param a annotation node data.
 * @param sceneElement <tf-graph-scene> polymer element.
 */
function update(aGroup, d: render.RenderNodeInfo, a: render.Annotation, sceneElement) {
  let cx = layout.computeCXPositionOfNodeShape(d);
  // Annotations that point to embedded nodes (constants,summary)
  // don't have a render information attached so we don't stylize these.
  // Also we don't stylize ellipsis annotations (the string '... and X more').
  if (a.renderNodeInfo && a.annotationType !== render.AnnotationType.ELLIPSIS) {
    stylize(aGroup, a.renderNodeInfo, sceneElement, Class.Annotation.NODE);
  }
  if (a.annotationType === render.AnnotationType.SUMMARY) {
    // Update the width of the annotation to give space for the image.
    a.width += 10;
  }
  // label position
  aGroup
    .select('text.' + Class.Annotation.LABEL)
    .transition()
    .attr('x', cx + a.dx + (a.isIn ? -1 : 1) * (a.width / 2 + a.labelOffset))
    .attr('y', d.y + a.dy);
  // Some annotations (such as summary) are represented using a 12x12 image tag.
  // Purposely omitted units (e.g. pixels) since the images are vector graphics.
  // If there is an image, we adjust the location of the image to be vertically
  // centered with the node and horizontally centered between the arrow and the
  // text label.
  aGroup
    .select('use.summary')
    .transition()
    .attr('x', cx + a.dx - 3)
    .attr('y', d.y + a.dy - 6);
  // Node position (only one of the shape selection will be non-empty.)
  positionEllipse(aGroup.select('.' + Class.Annotation.NODE + ' ellipse'), cx + a.dx, d.y + a.dy, a.width, a.height);
  positionRect(aGroup.select('.' + Class.Annotation.NODE + ' rect'), cx + a.dx, d.y + a.dy, a.width, a.height);
  positionRect(aGroup.select('.' + Class.Annotation.NODE + ' use'), cx + a.dx, d.y + a.dy, a.width, a.height);
  // Edge position
  aGroup
    .select('path.' + Class.Annotation.EDGE)
    .transition()
    .attr('d', (a) => {
      // map relative position to absolute position
      let points = a.points.map((p) => {
        return { x: p.dx + cx, y: p.dy + d.y };
      });
      return edge.interpolate(points);
    });
}

/**
 * Scene.
 */

/**
 * Select or create a sceneGroup and build/update its nodes and edges.
 *
 * Structure Pattern:
 *
 * <g class='scene'>
 *   <g class='core'>
 *     <g class='edges'>
 *       ... stuff from tf.graph.scene.edges.build ...
 *     </g>
 *     <g class='nodes'>
 *       ... stuff from tf.graph.scene.nodes.build ...
 *     </g>
 *   </g>
 *   <g class='in-extract'>
 *     <g class='nodes'>
 *       ... stuff from tf.graph.scene.nodes.build ...
 *     </g>
 *   </g>
 *   <g class='out-extract'>
 *     <g class='nodes'>
 *       ... stuff from tf.graph.scene.nodes.build ...
 *     </g>
 *   </g>
 * </g>
 *
 * @param container D3 selection of the parent.
 * @param renderNode render node of a metanode or series node.
 * @param sceneElement <tf-graph-scene> polymer element.
 * @param sceneClass class attribute of the scene (default='scene').
 */
export function buildGroupForScene(
  container,
  renderNode: render.RenderGroupNodeInfo,
  sceneElement: TfGraphScene,
  sceneClass?: string,
): d3.Selection<any, any, any, any> {
  sceneClass = sceneClass || Class.Scene.GROUP;
  let isNewSceneGroup = selectChild(container, 'g', sceneClass).empty();
  let sceneGroup = selectOrCreateChild(container, 'g', sceneClass);
  // core
  let coreGroup = selectOrCreateChild(sceneGroup, 'g', Class.Scene.CORE);
  let coreNodes = _.reduce(
    renderNode.coreGraph.nodes(),
    (nodes, name) => {
      let node = renderNode.coreGraph.node(name);
      if (!node.excluded) {
        nodes.push(node);
      }
      return nodes;
    },
    Array<any>(),
  );
  if (renderNode.node.type === NodeType.SERIES) {
    // For series, we want the first item on top, so reverse the array so
    // the first item in the series becomes last item in the top, and thus
    // is rendered on the top.
    coreNodes.reverse();
  }
  // Create the layer of edges for this scene (paths).
  edge.buildGroup(coreGroup, renderNode.coreGraph, sceneElement);
  // Create the layer of nodes for this scene (ellipses, rects etc).
  buildGroup(coreGroup, coreNodes, sceneElement);
  // In-extract
  if (renderNode.isolatedInExtract.length > 0) {
    let inExtractGroup = selectOrCreateChild(sceneGroup, 'g', Class.Scene.INEXTRACT);
    buildGroup(inExtractGroup, renderNode.isolatedInExtract, sceneElement);
  } else {
    selectChild(sceneGroup, 'g', Class.Scene.INEXTRACT).remove();
  }
  // Out-extract
  if (renderNode.isolatedOutExtract.length > 0) {
    let outExtractGroup = selectOrCreateChild(sceneGroup, 'g', Class.Scene.OUTEXTRACT);
    buildGroup(outExtractGroup, renderNode.isolatedOutExtract, sceneElement);
  } else {
    selectChild(sceneGroup, 'g', Class.Scene.OUTEXTRACT).remove();
  }
  // Library functions
  if (renderNode.libraryFunctionsExtract.length > 0) {
    let outExtractGroup = selectOrCreateChild(sceneGroup, 'g', Class.Scene.FUNCTION_LIBRARY);
    buildGroup(outExtractGroup, renderNode.libraryFunctionsExtract, sceneElement);
  } else {
    selectChild(sceneGroup, 'g', Class.Scene.FUNCTION_LIBRARY).remove();
  }
  tf_graph_scene.position(sceneGroup, renderNode);
  // Fade in the scene group if it didn't already exist.
  if (isNewSceneGroup) {
    sceneGroup.attr('opacity', 0).transition().attr('opacity', 1);
  }
  return sceneGroup;
}
export function getColors(colors) {
  Object.keys(colorStorage).forEach((key) => delete colorStorage[key]);
  Object.assign(colorStorage, colors);
}

export function getMatched(matched) {
  Object.keys(matchStorage).forEach((key) => delete matchStorage[key]);
  Object.assign(matchStorage, matched);
}

export function getUnMatched(unmatched) {
  Object.keys(unMatchStorage).forEach((key) => delete unMatchStorage[key]);
  Object.assign(unMatchStorage, unmatched);
}
